<template>
  <uv-keyboard @close="keyboardClose" :tooltip="tooltip" safeAreaInsetBottom ref="keyboard" :tips="tips" mode="number" @backspace="keyboardBackspace" @change="keyboardChange" @confirm="keyboardConfirm" @cancel="keyboardCancel"></uv-keyboard>

</template>
<script>
function throttle(func, wait, immediate = false) {
  let lastTime = 0; // 上次执行时间
  let timer = null; // 定时器

  return function (...args) {
    const now = Date.now();

    // 立即执行模式：如果是第一次执行，直接触发
    if (immediate && !lastTime) {
      func.apply(this, args);
      lastTime = now;
      return;
    }

    // 清除之前的定时器
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    // 计算剩余等待时间
    const remaining = wait - (now - lastTime);

    // 如果剩余时间 <= 0，说明可以执行了
    if (remaining <= 0) {
      func.apply(this, args);
      lastTime = now;
    } else if (!immediate) {
      // 延迟执行模式：设置定时器，在剩余时间后执行
      timer = setTimeout(() => {
        func.apply(this, args);
        lastTime = Date.now();
        timer = null;
      }, remaining);
    }
  };
}
export default {
  props: {
    tipsValue: {
      type: [Number, String],
      default: ''
    },
    tooltip: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      tips: ''
    }
  },
  methods: {
    open() {
      if (this.tipsValue == 0 || this.tipsValue == null) {
        this.tips = ''
      } else {
        this.tips = String(this.tipsValue)
      }
      this.$refs.keyboard.open()
    },
    close() {
      this.tips = ''
      this.$refs.keyboard.close()
    },
    keyboardChange(e) {
      let value = String(this.tips) + e
      this.tips = this.handleInput(value)
      this.$emit('u-change', this.tips)
    },
    keyboardClose() {
      this.tips = ''
      this.$emit('close', '')
    },
    keyboardCancel() {
      this.tips = ''
      this.$emit('cancelTap', '')
    },
    keyboardConfirm() {
      let num = Number(this.handleInput(this.tips)) || null
      this.$emit('confirmTap', num)
    },
    keyboardBackspace(e) {
      let value = String(this.tips)
      if (value.length > 0) {
        const newValue = value.substring(0, value.length - 1);
        this.tips = newValue
        this.$emit('u-change', this.tips)
      } else {
        uni.$uv.toast('已无内容可删除')
      }
    },
    handleInput(values) {
      let value = String(values)
      value = value.replace(/[^\d.]/g, '')
      value = value.replace(/^\./g, '')
      value = value.replace(/\.{2,}/g, '.')
      value = value.replace(/(\.\d{2})\d*/g, '$1')
      const dotIndex = value.indexOf('.');
      if (dotIndex !== -1) {
        value = value.substring(0, dotIndex + 3);
        value = value.replace(/\./g, (match, index) => index === dotIndex ? match : '');
      }
      if (value.length > 1 && value[0] === '0' && value[1] !== '.') value = value.replace(/^0+/, '0');
      return value
    },
  },
}
</script>
<style lang="">
</style>